package cn.net.sinodata.system.msghandler.process;

import cn.net.sinodata.common.core.enums.MsgParseHandlerTypeEnum;
import cn.net.sinodata.common.core.enums.TaskTypeEnum;
import cn.net.sinodata.common.core.utils.SpringUtils;
import cn.net.sinodata.system.domain.*;
import cn.net.sinodata.system.mapper.PmMonitorProductMapper;
import cn.net.sinodata.system.msghandler.exception.MsgParseException;
import cn.net.sinodata.system.msghandler.process.base.BaseMsgProcessHandler;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.Map;

/**
 * 外汇交易中心流程处理类（CSTP接口服务处理类）
 */
@Slf4j
public class CFETSMsgProcessHandler extends BaseMsgProcessHandler {

    // private CFETSMsgProcessHandler delegate; // 委托类

    public CFETSMsgProcessHandler(BmTransLogRecord bmTransLogRecord, BmTransLogMsg bmTransLogMsg, MsgParseHandlerTypeEnum handlerType) {
        super(bmTransLogRecord, bmTransLogMsg, handlerType);
    }

    @Override
    public Map<String, Object> getCommonInfo(BmTransLogRecord bmTransLogRecord, BmTransLogMsg bmTransLogMsg) throws MsgParseException {
        log.info("外汇交易中心获取公共信息-开始");
        HashMap<String, Object> commonInfoMap = new HashMap<>();
        // 报文解析
        String respMsg = bmTransLogMsg.getResponseMsg();
        Element element;
        try {
            element = msgParseHandler.parse(respMsg);
        } catch (Exception e) {
            log.error("报文解析失败:", e);
            throw new MsgParseException("报文解析失败:" + e.getMessage());
        }

        // 获取业务类型
        Element msgTypeElement = (Element)element.selectSingleNode("/message/header/MsgType");
        if (msgTypeElement != null && msgTypeElement.hasContent()) {
            String msgType = msgTypeElement.getText();
            commonInfoMap.put("MsgType", msgType);
        } else {
            log.warn(bmTransLogRecord.getTransSerial() + "报文没有MsgType，无法确认报文类型");
        }

        // 获取市场类型
        Element marketIndicatorElement = (Element)element.selectSingleNode("/message/body/MarketIndicator");
        if (marketIndicatorElement != null && marketIndicatorElement.hasContent()) {
            String marketIndicator = marketIndicatorElement.getText();
            commonInfoMap.put("MarketIndicator", marketIndicator);
        } else {
            log.warn(bmTransLogRecord.getTransSerial() + "报文没有MarketIndicator，无法确认产品类型");
        }

        // 获取成交编号
        Element execIDElement = (Element)element.selectSingleNode("/message/body/ExecID");
        if (execIDElement != null && execIDElement.hasContent()) {
            String execID = execIDElement.getText();
            commonInfoMap.put(TRANS_SERIAL, execID);
        } else {
            log.warn(bmTransLogRecord.getTransSerial() + "报文没有ExecID，报文缺失");
        }

        log.info("外汇交易中心获取公共信息-结束");
        return commonInfoMap;
    }

    @Override
    public TaskTypeEnum taskTypeHandle(BmTransLogRecord bmTransLogRecord, BmTransLogMsg bmTransLogMsg) throws Exception {
        log.info("外汇交易中心判断报文类型-开始");
        String msgType = (String)commonInfo.get("MsgType");
        // 判断任务类型
        log.info("外汇任务类型为:{}", msgType);
        TaskTypeEnum taskTypeEnum = null;
        // TODO 需更新成枚举值
        if ("8".equals(msgType)) { //交易下发
            taskTypeEnum = TaskTypeEnum.TRANS;
        } else if ("QR".equals(msgType)) { // 交易确认
            taskTypeEnum = TaskTypeEnum.CONFIRM;
        } else if ("QS".equals(msgType)) { // 交易清算
            taskTypeEnum = TaskTypeEnum.CLEARING;
        }
        log.info("外汇交易中心判断报文类型-结束");
        return taskTypeEnum;
    }

    @Override
    public PmMonitorProduct getMonitorProduct(BmTransLogRecord bmTransLogRecord, BmTransLogMsg bmTransLogMsg) throws Exception {
        log.info("获取监控产品信息-开始");
        String marketIndicator = (String)commonInfo.get("MarketIndicator");
        log.info("当前市场类型为：{}", marketIndicator);

        // 查询监控产品
        PmMonitorProduct pmMonitorProduct = pmMonitorProductMapper.selectOne(new QueryWrapper<PmMonitorProduct>().eq("biz_type", marketIndicator));
        log.info("获取监控产品信息-结束");
        return pmMonitorProduct;
    }

    @Override
    public void trans(BmTransSerial bmTransSerial, BmTransSubSerial bmTransSubSerial) {
        log.info("确认交易处理-开始");
        // TODO

        log.info("确认交易处理-结束");
    }

    @Override
    public void confirm(BmTransSerial bmTransSerial, BmTransSubSerial bmTransSubSerial) {
        // TODO
    }

    @Override
    public void clearing(BmTransSerial bmTransSerial, BmTransSubSerial bmTransSubSerial) throws Exception {
        throw new Exception("外汇交易中心不支持清结算业务");
    }
}
